//
//  AppDelegate.m
//  Car1
//
//  Created by Ardee on 15/11/14.
//  Copyright © 2015年 Ardee. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"

#import "CodePush.h"

#import "RCTBundleURLProvider.h"
#import "RCTRootView.h"

#import "UMMobClick/MobClick.h"
#import "RCTUmengPush.h"
#import "HQNetWorkingApi.h"

#import "LoadingViewController.h"

// 性别 0=>全部 1=>男 2=>女
typedef NS_ENUM(NSInteger, HomePostCategory) {
    HomePostCategoryAll = 0,
    HomePostCategoryMan,
    HomePostCategoryWomen,
};

@interface AppDelegate ()

@property (nonatomic, strong) NSDictionary *launchOptions;

@property (nonatomic, strong) ViewController *nativeRootController;
@property (nonatomic, strong) UIViewController *reactNativeRootController;
@property (nonatomic, strong) UIViewController *loadingController;

@property (nonatomic, assign) BOOL is_mine;
@property (nonatomic, assign) BOOL is_today;
@property (nonatomic, assign) BOOL is_month;
@property (nonatomic, assign) BOOL is_year;
@property (nonatomic, strong) UIView *aView;
@property (nonatomic, strong) UIView *bView;
@property (nonatomic, strong) UIView *cView;
@property (nonatomic, strong) UIView *dView;

@end

@implementation AppDelegate

static NSString *const ShowReactNativeContent = @"ShowReactNativeContent";

#pragma mark - applicaton life circle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self showReactNativeControllerIfInNeed];
    [self.window makeKeyAndVisible];
    [self registerForUmentWithAppKey:@"58f4a4d56e27a434920000be"];
    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    //获取deviceToken
    [RCTUmengPush application:application didRegisterDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    //获取远程推送消息
    [RCTUmengPush application:application didReceiveRemoteNotification:userInfo];
}

#pragma mark - custom methods

-  (void)restoreRootViewController:(UIViewController *)newRootController {
    [UIView transitionWithView:self.window duration:0.25 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
        BOOL oldState = [UIView areAnimationsEnabled];
        [UIView setAnimationsEnabled:NO];
        if (self.window.rootViewController!=newRootController) {
            self.window.rootViewController = newRootController;
        }
        [UIView setAnimationsEnabled:oldState];
    } completion:nil];
}

- (void)showReactNativeControllerIfInNeed {
    // 网络更新本地配置会有延迟，先根据本地配置进行展示，防止闪退
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    BOOL showRNContentAtFirst = [userDefaults boolForKey:ShowReactNativeContent];
    id containKey = [userDefaults objectForKey:ShowReactNativeContent];
    if (containKey!=nil) {
        if (showRNContentAtFirst) {
            self.window.rootViewController = self.reactNativeRootController;
        } else {
            self.window.rootViewController = self.nativeRootController;
        }
    } else {
        self.window.rootViewController = self.loadingController;
    }
    
    NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];
    NSString *bundleVersion = [infoPlist objectForKey:@"CFBundleVersion"];
    NSString *bundleIdentifer = [infoPlist objectForKey:@"CFBundleIdentifier"];
    [HQNetWorkingApi requestReviewInfoWithPlatform:@"1" channel:@"AppStore" appUniqueId:bundleIdentifer version:bundleVersion handler:^(NSDictionary *allHeaderFields, NSDictionary *responseObject) {
        NSInteger statusCode = [responseObject[@"code"] integerValue];
        if (statusCode>=200 && statusCode<=206) {
            // 请求成功的情况
            NSDictionary *dataDic = responseObject[@"data"];
            NSInteger reviewStatusCode = [dataDic[@"reviewStatus"] integerValue];
            if (reviewStatusCode==2) {
                // 已经通过审核
                [userDefaults setBool:YES forKey:ShowReactNativeContent];
            } else {
                // 没有通过审核
                [userDefaults setBool:NO forKey:ShowReactNativeContent];
            }
        } else {
            // 请求失败的情况
            [userDefaults setBool:NO forKey:ShowReactNativeContent];
        }
        // 根据缓存来展示RN内容
        BOOL showRNContent = [userDefaults boolForKey:ShowReactNativeContent];
        dispatch_async(dispatch_get_main_queue(), ^{
            // 切换主线程进行展示
            if (showRNContent) {
                [self restoreRootViewController:self.reactNativeRootController];
            } else {
                [self restoreRootViewController:self.nativeRootController];
            }
        });
    }];
}



#pragma mark - getter and setter

- (UIViewController *)loadingController {
    if (!_loadingController) {
        _loadingController = [[LoadingViewController alloc] init];
    }
    return _loadingController;
}

#pragma mark - 第三方


/**
 注册友盟服务
 
 @param appKey 友盟key
 */
- (void)registerForUmentWithAppKey:(NSString *)appKey {
    //注册友盟推送
    [RCTUmengPush registerWithAppkey:appKey launchOptions:self.launchOptions];
    UMConfigInstance.appKey = appKey;
    UMConfigInstance.channelId = @"App Store";
    //  UMConfigInstance.eSType=E_UM_GAME;//友盟游戏统计，如不设置默认为应用统计
    [MobClick startWithConfigure:UMConfigInstance];
    [MobClick setLogEnabled:YES];
}

/**
 懒加载
 
 @return React-Native的控制器
 */
- (UIViewController *)reactNativeRootController {
    if (!_reactNativeRootController) {
        _reactNativeRootController = [[UIViewController alloc] init];
        
        NSURL *jsCodeLocation;
#ifdef DEBUG
        jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
#else
        jsCodeLocation = [CodePush bundleURL];
#endif
        
        RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                            moduleName:@"hatsune"
                                                     initialProperties:nil
                                                         launchOptions:self.launchOptions];
        rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
        _reactNativeRootController.view = rootView;
    }
    return _reactNativeRootController;
}


/**
 懒加载
 
 @return Native的控制器
 */
- (ViewController *)nativeRootController {
    if (!_nativeRootController) {
        _nativeRootController = [[ViewController alloc] init];
    }
    return _nativeRootController;
}
- (UIView *)aView {
    if (!_aView) {
        _aView = [UIView new];
    }
    return _aView;
}
- (UIView *)bView {
    if (!_bView) {
        _bView = [UIView new];
    }
    return _bView;
}
- (UIView *)cView {
    if (!_cView) {
        _cView = [UIView new];
    }
    return _aView;
}
- (UIView *)dView {
    if (!_dView) {
        _dView = [UIView new];
    }
    return _dView;
}
@end
